<script src="{{ getAssets }}js/autocompleter/jquery.autocomplete.min.js?v={{ assets_version }}"></script>
<script src="{{ getAssets }}lodop/LodopFuncs.js?v={{ assets_version }}"></script>
<script>
var optometryData = new Object;  //保存配镜数据

optometryData.LSph = '';
optometryData.LCyl = '';
optometryData.RSph = '';
optometryData.RCyl = '';

function receiveFormData(d) {
	if(!d) return false;
	
	if(d.isProduct == 1) {
		receiveFormDataProduct(d);
	} else {
		for (var key in d){
			 val = d[key]
			 if(key == "Sex") {
				 $('input[name="Sex"]').each(function(){ if($(this).attr("value") == val) { $(this).prop("checked", true) }  });
			 }else{
				$("#"+key).val(val)
			 }
		 }
		 $('select').trigger('changed.selected.amui');
		 $("#formDoSubmitDialogPay").validator('destroy');
	}
}

$('#findProducts').click(function(){
	var url = '{{ urlfor "ProductsController.SelectProducts"}}';
	layer.open({
		type: 2,
		title: '选择产品',
		shadeClose: false,
		shade: 0.2,
		maxmin: true,
		shift: 1,
		area: ['95%', '90%'],
		content: url
	});
	return false;
});

$('#getProductRows').autocomplete({
    serviceUrl: '{{ urlfor "ProductsController.DataGrid"}}',
	type:'post',
	dataType:'json',
	transformResult : function (response, originalQuery) {
		if(response.iTotalDisplayRecords > 0) {
			return {
				suggestions: $.map(response.aaData, function(d) {
					if(d.Diopter && d.Astigmatism) {
						d.FullName = d.FullName;
					}
					return { value: d.FullName, data: d};
				})
			};
		} else  {
			return {suggestions:''}	
		}
	},
    onSelect: function (s) {
		if(checkIsSetGlassesNumber(s.data.TypeId)) {
			setGlassesNumber(0, s.data,s.data.TypeId);
			$('#getProductRows').val('');
			return false;
		}
		receiveFormDataProduct(s.data)
        $('#getProductRows').val('');
		
    },
	onSearchStart: function(p) {
		eyeType = $('#eye_type').val();
		
		p.lsph = optometryData.LSph;
		p.lcyl = optometryData.LCyl;
		p.rsph = optometryData.RSph;
		p.rcyl = optometryData.RCyl;
		
		return p;
	}
	
});

var pData;
function setGlassesNumber(index, productData,typeId) {
	
	if($('#is_customized').prop('checked')) {  //如果是订制镜片则不弹出度数选对框
		receiveFormDataProduct(productData);
		return false;
	}	

	pData = '';
	var url = '{{ urlfor "ProductsController.AttributeHtml"}}?typeid=' + typeId + '&lsph=' + optometryData.LSph+ '&lcyl=' + optometryData.LCyl+ '&rsph=' + optometryData.RSph+ '&rcyl=' + optometryData.RCyl;
    var index = layer.open({
           type: 2
           ,title: '选择屈散度数'
           ,shadeClose: false
		   ,skin: 'layui-layer-molv'
           ,shade: 0.2
           ,maxmin: true
           ,shift: 1
           ,area: ['98%', '98%']
		   ,zIndex: layer.zIndex //重点1
           ,content: url
    });
	layer.full(index);
	pData = productData;
	return false;
}

function setGlassesStandard(amount, diopter, astigmatism) {
	if(!pData) {
		return false;	
	}
	pData.Diopter = diopter;
	pData.Astigmatism = astigmatism;
	pData.Amount = amount;
	
	receiveFormDataProduct(pData);
}



{{if eq .optid 0}}
$('#Mobile').blur(function(){
	if($(this).val() == '') {
		return false;	
	}
	$.post('{{urlfor "ArchivesController.SelectArchives"}}', {"keyword":$(this).val()}, function(j){
		if (j.code == 1) {
			searcharchives()	
		}
	}, 'json')  
});
	//没有验光时
	{{if .arid}}
		$.post('{{urlfor "ArchivesController.ViewOne"}}/{{.arid}}', function(j){
			if (j.code == 0) {
				receiveFormData(j.data);
			}
		}, 'json');  
	{{end}}

{{else}}

$(function(){
	var index = layer.load(0, {shade: false});
	$.post('{{urlfor "OptometryController.ViewOne"}}/{{.optid}}', function(j){
		layer.close(index);
		if(j.code == 1) {
			layer.msg(j.msg);
			return false;
		}
		optometryData = j.data;
		receiveFormData(optometryData.Archives);
		
		$('#optometry_id').val(optometryData.Id);
	},'json');
});

{{end}}

$("#searcharchives").click(function(){
	searcharchives();
});  
  
$('#windowOut').click(function(){
	parent.layer.closeAll('iframe');
});
$('#business_id').on('change', function(){
	$('#BusinessName').val($(this).find(':selected').text())
});

$("#formDoSubmitDialogPay").validator({
  submit: function() {
	if(this.isFormValid()) {
		
		$('#payment_money_meter').val($('#payment_money').val()); //应收金额
		$('#arrears_money_meter').val(0);  //欠款
		$('#give_change_meter').val(0); //找零
		
		var rm = '';
		var plen = 0;
		$('.rm').each(function(){
			rm += $(this).val()+',';
			plen++;
		});
		if(plen <= 0) {
			layer.alert("请添加产品信息");
			return false;	
		}
		$('#rows_num').val(rm);
		
		//弹出支付类型框
		var fn  = function() {
			layer.open({
				type: 1
				, title: '<i class="fa fa-cog"></i>&nbsp;支付类型'
				, shade: 0
				, maxmin: true
				, zIndex :29891014
				, id: 'search_archives_dialog_pay'
				, area: ['600px', '310px']
				, content: $('#payType')
				, anim: 1 //动画类型
			});
		}
		var loads = layer.load(0, {shade: false});
		//验证库存信息
		$.post('{{ urlfor "InventoryController.CheckEntry" }}', $("#formDoSubmitDialogPay").serialize(), function(j) {
			layer.close(loads);
			if(j.code == 1) {
				var tips = '';
				for(i=0;i<j.data.length;i++) {
					tips += j.data[i] + '<br />';	
				}
				layer.confirm(tips + '是否继续添加！', {icon: 3, title:'提示'}, function(index){
				  fn();
				  layer.close(index);
				});
			} else {
				fn();	
			}
		});

	}
	return false;
  }
});


function searcharchives() {
	key = $("#Mobile").val();
	layer.open({
        type: 2
        , skin: 'layui-layer-molv'
        , title: '<i class="fa fa-cog"></i>&nbsp;查找资料'
        , shadeClose: true
        , shade: 0.2
		, moveOut : true
        , id: 'search_archives_dialog'
        , area: ['95%', '95%']
        , content: ['{{urlfor "ArchivesController.SelectArchives"}}?keyword=' + key]
        , anim: 1 //动画类型
		, zIndex: layer.zIndex
		,success: function(layero){
			console.log(layero)
		    layer.setTop(layero);
		}
    });
}


<!-- 增加和减少ROW -->
var total_row_id = 0;
var now_rows = 0;
//减少一条信息
$(document).on('click','.reduce_one',function(){
	var row_id = $(this).parent().parent().attr('id');
	//如果行内存在商品，弹出操作提示
	row_val = row_id.substr(4);
	if($('#product_id_'+row_val).val() == ''){
		$('#'+row_id).remove();
		calculate(total_row_id);
	}else{
		if(confirm('该行存在商品，确定要移除么？')){
			$('#'+row_id).remove();
			calculate(total_row_id);
		}else{
			return false;
		}
	}
	// now_rows --;
});

//验证是否为定制
$('#is_customized').change(function(){
	if($(this).prop('checked')) {  //确定要定制
		$('.glasses').attr('readonly', false).attr('required', true);
			
	} else {
		$('.glasses').attr('readonly', true).attr('required', false);	
	}
});

<!-- 增加和减少ROW END-->
function receiveFormDataProduct(data) {

	now_rows += 1;
	$('#view_row').remove();
	var product_id = data.Id;
	var product_name = data.FullName
	//var standard = data.Standard
	var suggested_price = 0;
	var original_price = data.SuggestedPrice;
	var diopter = data.Diopter ? data.Diopter : '';
	var astigmatism = data.Astigmatism ? data.Astigmatism : '';
	var model_number = data.ModelNumber;
	var colour_number = data.ColourNumber;
	var amount = data.Amount ? data.Amount : 1;
	var glasses = data.TypeId <= 30 ? 'glasses' : '';

	
	rowHtml = '<tr id="row_'+now_rows+'"><td style="text-align:center;">';
	rowHtml += '<input type="hidden" class="rm" value="'+now_rows+'" />';
	rowHtml += '<a href="javascript:void(0);" class="reduce_one"><i class="am-icon-minus"></i></a></td>';
	rowHtml += '<td><input type="hidden" name="Product['+now_rows+'][product_id]" id="product_id_'+now_rows+'" class="product_id" value="'+product_id+'" /><input type="text" name="Product['+now_rows+'][product_name]" id="product_name_'+now_rows+'" readonly="readonly" value="'+product_name+'" required/></td>';
	
	
	rowHtml += '<td><input type="number" class="'+ glasses +'" value="'+diopter+'" name="Product['+now_rows+'][diopter]"  readonly /></td>';  //屈光度
	rowHtml += '<td><input type="number" class="'+ glasses +'" value="'+astigmatism+'" name="Product['+now_rows+'][astigmatism]"  readonly /></td>';  //散光度
	
	rowHtml += '<td><input type="text" value="'+model_number+'" name="Product['+now_rows+'][model_number]"  readonly /></td>';  //规格
	rowHtml += '<td><input type="text" value="'+colour_number+'" name="Product['+now_rows+'][colour_number]" readonly /></td>';  //色号
	
	rowHtml += '<td><input type="text" name="Product['+now_rows+'][amount]" id="product_amount_'+now_rows+'" class="amount" onkeyup="calculate('+now_rows+')" value="'+ amount +'"/></td>';  //产品数量
	rowHtml += '<td><input type="text" name="Product['+now_rows+'][original_price]" id="product_original_price_'+now_rows+'" onkeyup="calculate('+now_rows+')" value="'+original_price+'" /></td>'; //产品原价
	rowHtml += '<td><input type="text" name="Product['+now_rows+'][discount_rate]" id="product_discount_rate_'+now_rows+'" onkeyup="calculate('+now_rows+')" value="100"/></td>';
	rowHtml += '<td><input type="text" name="Product['+now_rows+'][unit_price]" id="product_unit_price_'+now_rows+'" class="unit_price" readonly="readonly"/></td>'; //产品单价
	rowHtml += '<td><input type="text" name="Product['+now_rows+'][total_price]" id="product_total_price_'+now_rows+'" class="total_price" readonly="readonly"/></td>';  //总金额
	
	/*
	rowHtml += '<td><div class="divSelect"><select name="Product['+now_rows+'][warehouse_id]" >';
	
	{{range $k,$v := .wareHouse}}
		rowHtml += '<option value="{{$v.Id}}">{{$v.WarehouseName}}</option>';
    {{end}}
												
	rowHtml += '</select></div></td>';
	*/
	rowHtml += '</tr>'
	
	$('#add_products').append(rowHtml);

	calculate(now_rows);
	
	$('#is_customized').change();  //固定化设置
	//parent.layer.iframeAuto(index);
}


<!-- 根据选项计算价格 -->
function calculate(param){
	if($('#product_id_'+param).val() != '' && $('#product_id_'+param).val() != '0'){
		//先对当前Row进行计算
		var amount = $('#product_amount_'+param).val();  //产品数量
		var original_price = $('#product_original_price_'+param).val();  //产品原价
		var discount_rate = $('#product_discount_rate_'+param).val();  //产品折扣额%比
		
		var unit_price = cal_discount_money(original_price, 1, discount_rate);//折扣额计算单价
		$('#product_unit_price_'+param).val(unit_price);  //产品单价
		
		var total_price = new Number(amount) * new Number(unit_price);// 计算总金额
		$('#product_total_price_'+param).val(total_price.toFixed(2));
		
		
		var total_prime_price = 0.00;
		$('.total_price').each(function(k, v){
			//实际应付总价（不包含其它费用）
			if($(v).val() != '' || $(v).val() != '0.00' || $(v).val() != '0'){
				total_prime_price += new Number($(v).val());
			}
		});
		$('#total_money').val(total_prime_price.toFixed(2));
		cal_discount_price();
	}else{
		return false;
	}
}
<!-- 根据选项计算价格 END-->

<!-- 根据其它费用计算最终应付金额 -->
function cal_discount_price(){
	var total_money = $('#total_money').val();
	var changes_money = $('#changes_money').val();
	
	payment_money = new Number(total_money) - new Number(changes_money);
	$('#payment_money').val(payment_money.toFixed(2));
}
<!-- 根据其它费用计算最终应付金额 END-->

<!-- 计算折扣额 -->
/**
 * 根据原价和折扣率计算出折扣额
 * @unit_price		原价
 * @amount			数量
 * @discount_rate	折扣率
 */
function cal_discount_money(unit_price, amount, discount_rate){
	var product_discount = 0;
	if(discount_rate == 0){
		product_discount = 0;
	}else{
		product_discount = (unit_price * amount) * (discount_rate/100);
	}
	return parseFloat(product_discount).toFixed(2);
}
<!-- 计算折扣额 END-->
//现金付款
function set_cash_money_meter() {
	var cash_money_meter = $('#cash_money_meter').val();  //支付现金
	cash_money_meter = new Number(cash_money_meter);
	var payment_money_meter = $('#payment_money_meter').val();  //须付金额
	payment_money_meter = new Number(payment_money_meter);
	
	var n = 0
	
	$('#arrears_money_meter').val(n);
	$('#give_change_meter').val(n);	
	if(cash_money_meter>=payment_money_meter)  {  //需要计算找零
		n = parseFloat((cash_money_meter - payment_money_meter)).toFixed(2);
		$('#give_change_meter').val(n);	
	} else {  //计算欠款
		n = parseFloat((payment_money_meter - cash_money_meter)).toFixed(2);
		$('#arrears_money_meter').val(n);	
	}
	
	return false;
}

function confirm_pay(t) {
	var payType = $(t).data("pay");
	var cash_money_meter = $('#cash_money_meter').val();  //支付现金
	cash_money_meter = new Number(cash_money_meter);
	
	var payment_money_meter = $('#payment_money_meter').val();  //须付金额
	payment_money_meter = new Number(payment_money_meter);
	
	switch(payType) {
		case 1:break;//刷卡支付
		case 2:break;//微信支付
		case 3:break;//支付宝支付
		case 4:
			if(cash_money_meter == 0) {
				alert('请填写现金支付金额');
				return false;
			}
		break;//现金支付
	}
	$('#payment_type').val(payType);  //设置支付类型
	$('#cash_money').val(cash_money_meter); //设置现金金额
	
	var needMoney = payment_money_meter;
	
	if(cash_money_meter > 0) { //计算支付除现金外支付金额
		needMoney = parseFloat((payment_money_meter - cash_money_meter)).toFixed(2);
	} 
	$('#payment_type_money').val(needMoney);
	
	//开始提交保存数据
	$('.confirm_pay').addClass('am-disabled'); //禁用按钮
	$.post('{{ urlfor "RetailController.AddSales"}}', $('#formDoSubmitDialogPay').serialize(), function(j){
		if(j.code == 1) {
			layer.msg(j.msg);	
			$('.confirm_pay').removeClass('am-disabled'); //取消禁用按钮
		} else {
			if(confirm('保存成功，是否需要打印单据?')) {
				//执行打印尺寸规格210*140
				$.post('{{ urlfor "RetailController.Printer" }}/'+j.data, function(j){
					if(j.code == 1) {
						layer.msg(j.msg);
						return false;	
					}
					createRetailPrinter(j.data);
					setTimeout(function(){
						layer.closeAll();
						location = '/retail/add';
					}, 1000);
				}, 'json');
			} else {
				layer.closeAll();
				location = '/retail/add';
			}
		}
	},'json');
	
	return false;
}
//验光数据
$('#view-optometry').click(function(){
	var opt_id = new Number($('#optometry_id').val());
	var arc_id = new Number($('#Id').val());
	
	if(opt_id == 0 && arc_id == 0) {
		layer.msg('请选择一个客户或验光信息！');
		return false;	
	}
	
	height = "90%";
	layer.open({
		type: 2
		, title: '验光数据'
		, shade: 0.2
		, id: 'viewOptometry_dialog'
		, area: ['96%', height]
		, content: ['{{ urlfor "OptometryController.View"}}?opt_id='+opt_id+'&arc_id='+arc_id]
		, anim: 1 //动画类型
	});
	return false;
});
//历史消费
$('#view-consumption').click(function(){
	
	var opt_id = new Number($('#optometry_id').val());
	var arc_id = new Number($('#Id').val());
	
	if(opt_id == 0 && arc_id == 0) {
		layer.msg('请选择一个客户或验光信息！');
		return false;	
	}
	
	height = "90%";
	layer.open({
		type: 2
		, title: '验光数据'
		, shade: 0.2
		, id: 'viewOptometry_dialog'
		, area: ['96%', height]
		, content: ['{{ urlfor "RetailController.View"}}?opt_id='+opt_id+'&arc_id='+arc_id]
		, anim: 1 //动画类型
	});
	
	return false	
});

</script>